/* 封装axios用于发送请求 */
import axios from 'axios'
import { Toast } from 'vant'
import store from '@/store'
import router from '@/router'

// 创建一个新的axios实例
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000000
})

// 添加请求拦截器
request.interceptors.request.use(function (config) {
  Toast.loading({
    message: '请求中...',
    forbidClick: true,
    loadingType: 'spinner',
    duration: 0
  })
  // 添加请求头
  const platform = store.getters['user/getPlatform']
  if (platform) config.headers.Platform = platform
  // 添加token
  const token = store.getters['user/getToken']
  if (token) config.headers.Token = token
  return config
}, function (error) {
  // 对请求错误做些什么
  Toast.fail(error.message)
  // return Promise.reject(error)
  return { data: null }
})

// 添加响应拦截器
request.interceptors.response.use(function (response) {
  const { data } = response
  // 请求成功
  if (data.status === 200) {
    Toast.clear()
    return data.data
  }
  // 登录超时
  if (data.status === 401) {
    store.commit('user/delToken')
    if (router.currentRoute.path !== '/login') {
      router.replace({
        path: '/login',
        query: { redirect: router.currentRoute.fullPath }
      })
    }
    Toast.fail(data.message || '登录超时')
  }

  // 业务错误提示
  Toast.fail(data.message || '后端接口错误')
  return Promise.reject(data.message)
}, function (error) {
  Toast.fail(error.message)
  return { data: null }
})

/**
 * 发送GET请求
 */
export function get (url, param) {
  return request.get(url, { params: param })
}

/**
 * 发送POST请求,form-data
 */
export function postFrom (url, params) {
  return request.post(url, params, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  })
}

/**
 * 发送POST请求,发送JSON报文体
 */
export function postJSON (url, params, data) {
  return request.post(url, { 'Content-Type': 'application/json;charset=UTF-8' }, data)
}

export default request
